﻿using P2P.Main.Model;
using P2P.Main.Session;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Main.Handler
{
    public class PingHandler
    {
        private ApiProtocol apiProtocol;

        public PingHandler(ApiProtocol apiProtocol)
        {
            this.apiProtocol = apiProtocol;
        }

        /// <summary>
        /// Ping命令应答处理
        /// </summary>
        public void PingAck() 
        {
            string AccountId = (string)apiProtocol.Params["AccountId"];

            ActiveNode activeNode = ActiveNodeSessionManager.Instance.Find(AccountId);

            if (activeNode == null)
            {
                return;
            }

            for (int i = 0; i < ActiveNodeSessionManager.Instance.ClientKBuckets.Count; ++ i) 
            {
                for (int j = 0; j < ActiveNodeSessionManager.Instance.ClientKBuckets[i].Count; ++ j) 
                {
                    if (ActiveNodeSessionManager.Instance.ClientKBuckets[i][j].Id.Equals(AccountId)) 
                    {
                        ActiveNode node = ActiveNodeSessionManager.Instance.ClientKBuckets[i][j];
                        ActiveNodeSessionManager.Instance.ClientKBuckets[i].RemoveAt(j);
                        ActiveNodeSessionManager.Instance.ClientKBuckets[i].Add(node);

                        lock (ActiveNodeSessionManager.Instance.AsyncDelayDeleteNodes) 
                        {
                            foreach (var bucketIndex in ActiveNodeSessionManager.Instance.AsyncDelayDeleteNodes.Keys)
                            {
                                ActiveNodeSessionManager.Instance.AsyncDelayDeleteNodes[bucketIndex] = ActiveNodeSessionManager.Instance.AsyncDelayDeleteNodes[bucketIndex].FindAll(n => !n.Id.Equals(node.Id));
                            }
                        }
                    }
                }
            }
        }
    }
}
